package com.hc.websocket.tomcatws;

import cn.hutool.extra.spring.SpringUtil;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import java.util.Map;

/**
 * 用于在 WebSocket 握手过程中将 HTTP 会话属性传递到 WebSocket 会话中
 * 可以在握手过程中访问和设置 HTTP 会话属性，从而在 WebSocket 会话中使用这些属性。
 * 从http会话中获取token并获取用户信息
 */
@Component
public class BootWebSocketInterceptor extends HttpSessionHandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
                                   Map<String, Object> attributes) throws Exception {
        // 接受前端传来的参数
        String token = ((ServletServerHttpRequest) request).getServletRequest().getParameter("Authorization");
        // if (StringUtils.isEmpty(token)) {
        //     return false;
        // }
        // TODO 从token中获取用户信息
        //将参数放到attributes
        attributes.put("user_id", 34L);
        return super.beforeHandshake(request, response, wsHandler, attributes);
    }

}
